package com.example.service;

import com.example.domain.Course;
import com.example.repository.CourseRepository;
import com.example.util.EasyuiResult;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class CourseService {
    
    @Autowired
    private CourseRepository courseRepository;
    
    @Transactional
    public EasyuiResult<Course> getAllList(String sortColumn, String order) {
        Sort sort = new Sort(Sort.Direction.valueOf(order), sortColumn);
        final Iterable<Course> all = courseRepository.findAll(sort);
        final ArrayList<Course> courses = Lists.newArrayList(all);
        EasyuiResult<Course> result = new EasyuiResult((long)courses.size(), courses);
        return result;
    }
    
    @Transactional
    public void delete(final int id) {
        courseRepository.deleteById(id);
    }
    
    
    @Transactional
    public int add(final String name) {
        Course course = new Course();
        course.setName(name);
        final Course save = courseRepository.save(course);
        return save.getId();
    }
    
    public List<Course> getAllCourses() {
        final Iterable<Course> all = courseRepository.findAll();
        return Lists.newArrayList(all);
    }
    
    public Course getById(final int courseid) {
        return courseRepository.findById(courseid).orElseGet(Course::new);
    }
    
    public List<Course> findAllById(final Set<Integer> ids) {
        final Iterable<Course> all = courseRepository.findAllById(ids);
        return Lists.newArrayList(all);
    }
}
